﻿/*
 *  ChgDoc CMS - GNU General Public License, version 3 (GPL-3.0)
 *  Copyright (C)  2012. Ian Quigley
 *  
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *  
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SqliteORM;
using ChgDoc.Entity;
using System.Dynamic;

namespace ChgDoc.Entity
{
    [Table]
    public class ArticleLocation : TableBase<ArticleLocation>
    {
        [ForeignKey( typeof( Article ) )]
        public long ArticleId { get; set; }

        [ForeignKey( typeof( Location ) )]
        public long LocationId { get; set; }

        [Field]
        public int SortOrder { get; set; }
        
        internal static void Add( long articleId, long locationId, int sortOrder = 0 )
        {
            Do( ad => ad.CreateUpdate( articleId, locationId, sortOrder ) );
        }

        internal static void Delete( long articleId, long locationId )
        {
            Do( ad => ad.Delete(Where.And(Where.Equal("ArticleId", articleId), Where.Equal("LocationId", locationId )) ));
        }


        internal static List<ArticleSortDisplay> ArticlesFor(long locationId)
        {
            List<ArticleSortDisplay> results = new List<ArticleSortDisplay>();

            using (var sql = new DirectSql())
            {
                sql.Execute("select a.Id, a.Title, al.SortOrder from article a join articlelocation al on al.articleid = a.id where al.locationid = " + locationId + " order by al.sortorder",
                    objArr =>
                    {
                        var row = new ArticleSortDisplay();
                        row.ArticleId = (long)objArr[0];
                        row.Title = (string)objArr[1];
                        row.SortOrder = (Convert.IsDBNull(objArr[2]) ? 0 : (int)objArr[2]) ;
                        results.Add(row);

                        return true;
                    });
            }

            return results;
        }

        
    }

    public class ArticleSortDisplay
    {
        public long ArticleId { get; set; }
        public string Title { get; set; }
        public int SortOrder { get; set; }
    }
}